package ;

import Counter;
import haxe.Timer;

/**
 * ...
 * @author 
 */

class TimeCounter extends Counter
{
	private var mElaps: Bool;
	private var mInterval: Int;
	private var mActive: Bool;
	private var mTimeout: Int;
	

	public function new(period: Int, start: Int, ?finish: Int) 
	{
		super();
		
		Set(start);
				
		mTimeout = 0;
		mInterval = period;
		mActive = false;

		mElaps = false;
		if (finish != null) {
			mTimeout = finish;
			
			if (finish <= start)
				mElaps = true;
		}
	}
	
	
	public function Start(?start: Int)
	{
		if (!mActive) {
			mActive = true;
			
			if (start != null) {
				Set(start);
			}
			
			Timer.delay(Timeout, mInterval);
		}
	}
	
	
	public function Stop()
	{
		mActive = false;
	}
	
	
	public function IsActive(): Bool
	{
		return mActive;
	}
	
	
	private function Timeout(): Void
	{
		//trace("timeout");
		
		if (mElaps) {
			Add(-mInterval);
			if (Get() <= mTimeout) {
				mActive = false;
				Set(mTimeout);
				
				// to do: call the handler
			}
		} else {
			Add(mInterval);
			if (Get() >= mTimeout) {
				mActive = false;
				Set(mTimeout);
				
				// to do: call the handler				
			}
		}
		
		if (mActive) {
			Timer.delay(Timeout, mInterval);
		}
	}
}